#include <iostream>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <memory.h>
#include <unistd.h>

int main(int args, char *argv[])
{
    if (args != 3)
    {
        std::cout << "please input ip and port" << std::endl;
        exit(1);
    }
    uint16_t port = atoi(argv[2]);
    std::string ip = argv[1];
    std::string message;
    bool alive = false; // 判断是否连接着
    int sock = 0;
    while (1)
    {
        if (!alive)
        {
            sock = socket(AF_INET, SOCK_STREAM, 0);
            if (sock < 0)
            {
                std::cout << "create socket failed" << std::endl;
                exit(2);
            }
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = htons(port);
            server.sin_addr.s_addr = inet_addr(ip.c_str());

            // 申请连接
            if (connect(sock, (struct sockaddr *)&server, sizeof server) < 0)
            {
                std::cerr << "connect error" << std::endl;
                exit(3);
            }
            std::cout << "connect success" << std::endl;
            alive = true; // 连接成功了，所以活过来了
        }
        std::cout << "请输入信息# ";
        std::getline(std::cin, message);
        if (message == "quit")
            break;

        // send和recv和read、write有点像，就是多了个是否阻塞（？
        ssize_t s = send(sock, message.c_str(), message.size(), 0);
        if (s > 0)
        {
            char buffer[1024];
            ssize_t s = recv(sock, buffer, sizeof buffer, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                std::cout << "回显# " << buffer << std::endl;
            }
            else if (s == 0)
            {
                alive = false;
                // 关闭连接
                close(sock);
            }
        }
        else
        {
            alive = false;
            close(sock);
        }
    }
}